package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JPanel;

import model.Macro;
import model.MacroList;
import model.Variable;

public class MacroView extends JPanel implements ActionListener {
	private static final long serialVersionUID = -281204369866166477L;
	private JButton newMacro = new JButton("New");
	private JButton deleteMacro = new JButton("Delete");

	private JList list = new JList();

	public MacroView() {
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		this.setAlignmentX(LEFT_ALIGNMENT);
		this.add(makeMacroSet());
		this.add(makeButtons());
	}

	private JComponent makeMacroSet() {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.setAlignmentX(LEFT_ALIGNMENT);
		panel.add(makeList());
		return panel;
	}

	private JComponent makeButtons() {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		panel.setAlignmentX(LEFT_ALIGNMENT);
		newMacro.addActionListener(this);
		deleteMacro.addActionListener(this);
		panel.add(newMacro);
		panel.add(deleteMacro);
		return panel;
	}

	private JComponent makeList() {
		refresh();
		return list;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == newMacro) {
			new MacroEditor(this);
		} else if (e.getSource() == deleteMacro) {
			Object[] remove = list.getSelectedValues();
			for (Object item : remove) {
				String name = String.valueOf(item).split(" ")[0];
				MacroList.getInstance().removeMacro(name);
			}
			MacroList.getInstance().store();
			refresh();
		}

	}

	public void refresh() {
		Vector<String> data = new Vector<String>();
		for (Macro macro : MacroList.getInstance().getMacro()) {
			data.add(getMacroSignatur(macro));
		}
		list.setListData(data);
	}

	private String getMacroSignatur(Macro macro) {
		StringBuffer buf = new StringBuffer(macro.getName()).append(" ");
		for (Variable var : macro.getVariable()) {
			buf.append(var.getName()).append(" ");
		}
		return buf.toString();
	}
}
